<?php

namespace app\api\controller;
use think\Db;
class Login extends Base {
    /**
     * 账号密码登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0参数错误，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功
     */
    public  function userLogin(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['pass'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $pass = $_POST['pass'];
        if(preg_match("/^1[3456789]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json_encode(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                if(empty($username)){
                    return json_encode(['status'=>3,'msg'=>'该手机号未注册，无法登录']);
                }else{
                    if($username['user_password'] != md5($pass)){
                        return json_encode(['status'=>4,'msg'=>'密码输入错误']);
                    }else{
                        if($username['user_status'] == 3){
                            return json_encode(['status'=>4,'msg'=>'您的账号被冻结，请联系管理员']);
                        }
                        if($username['user_del'] == 2){
                            return json_encode(['status'=>4,'msg'=>'您的账号已被删除！']);
                        }
                        //更新token
                        $token = md5(date('YmdHis') . rand(100000,999999));
                        Db::table('up_u_user')->where('user_phone',$phone)
                            ->update(['user_token'=>$token]);
                        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
//                        ---------
                        $rytoken = $this->rongyun($username['user_id'],$username['user_username'],$username['user_image']);
                        $username['rytoken'] = $rytoken['token'];
//                        ------------
                        return json_encode(['status'=>200,'msg'=>$username]);
                    }
                }
            }
        }else{
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
    }

    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是修改密码或忘记密码 2是注册或更换手机号)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
    public  function getPhoneCode(){//echo 1;die;
        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['type'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $time = $_SERVER['HTTP_REQDATE'];
        $reqKey = $_SERVER['HTTP_REQKEY'];
        $appId = "A60824974958171";
        $appkey = "9KI962A0-YF56-W4OU-9635-6D57B0CCE811";
        $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
        if($myreqKey != $reqKey){
            return json_encode(['status'=>1,'msg'=>'非法来源']);
        }
        $num = rand(1000,9999);
        $phone = $_POST['phone'];
        $type = $_POST['type'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username) && $type==1){
            return json_encode(['status'=>21,'msg'=>'没有此手机号码用户']);
        }
        if(!empty($username) && $type==2){
            return json_encode(['status'=>22,'msg'=>'已经有此手机号码用户']);
        }
        $sendres = $this->duaxin($phone,$num);
        if($sendres['code'] != '00000'){
            return json_encode(['status'=>3,'msg'=>$sendres['msg']]);
        }else {
            //=============================
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'status' => 0]);
            } else {
                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
            }
            if (!$res) {
                return json_encode(['status' => 31, 'msg' => '数据库操作失败']);
            }
            //===============================================
            return json_encode(['status' => 200, 'msg' => md5($num)]);
        }
    }

    /**
     * 注册
     * @return bool
     * 参数：phone,code,password
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，4有其他未填项，5插入登录表失败，200成功
     */

    public  function userReg(){
        header("Access-Control-Allow-Origin:*");
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $pass = $_POST['password'];
        $type = $_POST['type'];//普通用户还是经纪人
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>3,'msg'=>'已经有此手机号码用户']);
        }
        if($pass=='' || $code==''){
            return json_encode(['status'=>4,'msg'=>'有未填项，请检查']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $url =  http_type ();
        $data['user_password'] = md5($pass);
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user_type'] = $type;
        $data['user_username'] = '用户' . rand(1000,9999);
        $data['user_image'] = $url . '/uploads/images/user2.png';
        if($type == 1){
            $data['user_status'] = 1;
            $data['user_image'] = $url . '/uploads/images/user1.png';
        }
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')
                ->where('user_id',$id)
                ->find();
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
//
            $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
            $user['rytoken'] = $rytoken['token'];
//
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
        }
    }
    /**
     * 忘记密码：forgetPass
     * @return bool
     * 参数：phone,code，newpass
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function forgetPass(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $new = $_POST['newpass'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code == '' || $new == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        if($username['user_status'] == 3){
            return json_encode(['status'=>4,'msg'=>'您的账号被冻结，请联系管理员']);
        }
        if($username['user_del'] == 2){
            return json_encode(['status'=>4,'msg'=>'您的账号已被删除！']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_password'=>md5($new),'user_token'=>$token]);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
//
            $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
            $user['rytoken'] = $rytoken['token'];
//
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>3,'msg'=>'密码重置失败']);
        }
    }

    /**
     * 关于我们和注册协议：regAndAbout
     */
    public function regAndAbout (){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        $data = Db::table('up_about')
            ->where('id',$type)
            ->find();
        return json_encode(['status'=>200,'msg'=>$data]);
    }

    /**
     * location 自动定位返回id：location
     * $location  地区名称
     */
    public function location (){
        extract(input());
        $res = array();
        if(isset($sheng)){
            $shengID = Db::table('up_area')
                ->where('district',$sheng)
                ->value('district_id');
            $res['sheng'] = $shengID;
        }
        if(isset($shi)){
            $shiID = Db::table('up_area')
                ->where('district',$shi)
                ->value('district_id');
            $res['shi'] = $shiID;
        }
        if(isset($qu)){
            $quID = Db::table('up_area')
                ->where('district',$qu)
                ->value('district_id');
            $res['qu'] = $quID;
        }
        if(isset($street)){
            $streetID = Db::table('up_area')
                ->where('district',$street)
                ->value('district_id');
            $res['street'] = $streetID;
        }
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 生成省市区json数据：makeJson
     * @return string
     */
    public function makeJson()
    {
//        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        $area = file_get_contents('static/area.json');
        $area2 = json_decode($area,true);
        return json_encode($area2);
//        set_time_limit(0);
//        $pro = Db::table('up_area')
//            ->where('pid',1)
////            ->where('district_id',1001)
//            ->field('district_id id,district name')
//            ->select();
//        foreach($pro as $k=>$v){
//            $pro[$k]['parentId'] = 0;
//            $city = Db::table('up_area')
//                ->where('pid',$v['id'])
//                ->where('level',2)
//                ->field('district_id id,district name,pid parentId')
//                ->select();
//            foreach ($city as $kk=>$vv){
//                $city[$kk]['sub'] = Db::table('up_area')
//                    ->where('pid',$vv['id'])
//                    ->where('level',3)
//                    ->field('district_id id,district name,pid parentId')
//                    ->select();
//                foreach ($city[$kk]['sub'] as $kkk=>$vvv){
//                    $city[$kk]['sub'][$kkk]['sub'] = Db::table('up_area')
//                        ->where('pid',$vvv['id'])
//                        ->where('level',4)
//                        ->field('district_id id,district name,pid parentId')
//                        ->select();
//                }
//            }
//            $pro[$k]['sub'] = $city;
//
//        }
//        return json_encode($pro);
    }
    /**
     * 获取所有城市：getCitys
     * @return string
     */
    public function getCitys(){
        $res = Db::table('up_area')
            ->where('level',2)
            ->field('district_id id,district city')
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 获取热门城市：TODO:添加个字段
     * @return string
     */
    public function getHotCitys(){
        $res = Db::table('up_area')
            ->where('level',2)
            ->where('hot',1)
            ->field('district_id id,district city')
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /*====自动定位End=====*/

    public function test(){
        $aa = array('今天','明天');
        $bb = array('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23');
        $cc = array('00','15','30','45');
        foreach ($aa as $k=>$v){
            $a[$k]['district'] = $v;
            $a[$k]['district_id'] = $k+1;
            foreach ($bb as $k2=>$v2){
                $b[$k2]['district'] = $v2;
                $b[$k2]['district_id'] = $k2;
                foreach ($cc as $k3=>$v3){
                    $c[$k3]['district'] = $v3;
                    $c[$k3]['district_id'] = $k3;
                }
                $b[$k2]['subDistrict'] = $c;
            }
            $a[$k]['subDistrict'] = $b;
        }
		$a[2]['district'] = '立即预约';
        $a[2]['district_id'] = 0;
        $aaa = json_encode($a);
        echo $aaa;
    }
}